package com.lysj.admin.cus.wxcustomer.util;

import cn.hutool.core.util.RandomUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lysj.admin.cus.wxcustomer.domain.WxCustomer;
import com.lysj.admin.cus.wxcustomer.service.WxCustomerService;
import com.lysj.admin.utils.exception.BaseException;
import com.lysj.admin.utils.json.JacksonUtil;
import com.lysj.admin.utils.web.HttpUtil;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.admin.utils.web.Resp;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 20:04 2019/3/4
 * @ Description:
 **/

public class WxAuzLogin {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @Resource
    private WxCustomerService wxCustomerService;

    private static final String redict_url = "https://diet.lingyundata.com/static/ordering/";
    private static final String applet_app_id = "wx7a42f66de632b299"; //小程序appid
    private static final String applet_app_secret = "77c77b373402521e11f8fe5b586e6884"; //小程序app私钥
    private static final String applet_access_token_url = "https://api.weixin.qq.com/sns/jscode2session"; //小程序授权链接
    private static final String get_user_info_url = "https://api.weixin.qq.com/sns/userinfo";

    private static final Type type = new TypeToken<Map<String, String>>() {
    }.getType();

    private static Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);


    public void wxLogin() throws IOException {
        StringBuilder sb = null;
        response.setCharacterEncoding("UTF-8");
        String state = request.getParameter("state"); // 获取要跳转的页面
        String code = request.getParameter("code");
        sb = new StringBuilder(redict_url);
        //通过微信接口返回的User
        WxCustomer wxCustomer = getUserInfo(code);
        //通过数据库查询返回的User,数据库还没有数据,新建一个用户
        WxCustomer userQuery = wxCustomerService.getRepository().findByOpenId(wxCustomer.getOpenId());
        if (userQuery == null) {
            userQuery = wxCustomerService.getRepository().saveAndFlush(wxCustomer);
        }
        sb.append("?customerId=" + userQuery.getId());
        response.sendRedirect(sb.toString());
    }


    public static WxCustomer getUserInfo(String code) {
        WxCustomer wxCustomer = new WxCustomer();
        // 第二步：通过code换取网页授权access_token
        Map<String, String> map = getOpenId(code);
        String openId = map.get("openid");
        String access_token = map.get("access_token");
        if (ParamUtil.isBlank(openId) || ParamUtil.isBlank(access_token)) {
            throw new BaseException("授权失败", Resp.Status.INNER_ERROR.getCode());
        }
        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        StringBuilder sb = new StringBuilder();
        sb.append("access_token=").append(access_token).append("&openid=").append(openId).append("&lang=zh_CN ");
        String userinfoJson = HttpUtil.sendGet(get_user_info_url, sb.toString());
        userinfoJson = userinfoJson.replace("[]", "\"\"");
        Map<String, String> userinfoMap = new Gson().fromJson(userinfoJson, type);
        if (ParamUtil.isBlank(userinfoMap.get("openid"))) {
            throw new BaseException("获取用户信息失败", Resp.Status.INNER_ERROR.getCode());
        }
        // 将获取到的用户信息返回出去
        wxCustomer.setOpenId(userinfoMap.get("openid"));
        wxCustomer.setNickName(emojiFilter(userinfoMap.get("nickname")));
        wxCustomer.setHeadPhoto(userinfoMap.get("headimgurl"));
        wxCustomer.setCity(userinfoMap.get("city"));
        wxCustomer.setCreateTime(new Date());
        return wxCustomer;
    }


    public static Map<String, String> getOpenId(String code) {
        Map<String, String> map;
        if (ParamUtil.isBlank(code)) {
            throw new BaseException("参数异常,请重新授权", Resp.Status.INNER_ERROR.getCode());
        }
        StringBuilder sb = new StringBuilder();
        sb.append("appid=").append(applet_app_id).append("&secret=").append(applet_app_secret).append("&js_code=").append(code).append("&grant_type=authorization_code");
        String tokenJson = HttpUtil.sendGet(applet_access_token_url, sb.toString());
        map = JacksonUtil.toStringMap(tokenJson);
        return map;
    }




    //过滤表情等特殊字符
    private static String emojiFilter(String source) {
        if (source == null) {
            source = "";
        }
        Matcher emojiMatcher = emoji.matcher(source);
        if (emojiMatcher.find()) {
            source = emojiMatcher.replaceAll("");
            if (source == null || source.trim().equals("")) {
                source = "点餐用户" + RandomUtil.randomNumbers(6);
            }
        }
        return source;
    }

}
